package com.dragon.backstage.aspect;

import cn.dev33.satoken.stp.StpUtil;
import com.dragon.backstage.service.LoginService;
import com.dragon.common.annotation.AuthPermission;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * API权限校验切面
 *
 * @author dragon
 * @version 1.0
 * @date 2024/8/5 14:37
 */
@Slf4j
@Aspect
@Component
public class AuthPermissionAspect {

    @Resource
    private LoginService loginService;

    /**
     * 处理请求前执行
     */
    @Before(value = "@annotation(authPermission)")
    public void boBefore(JoinPoint joinPoint, AuthPermission authPermission) {
        log.warn("***** API权限校验切面 *****");

        String permission = authPermission.value();
        log.warn("AuthPermissionAspect 接口权限标记 {}", permission);

        if (StringUtils.isNotBlank(permission)) {
            String account = loginService.getAccount();
            log.warn("AuthPermissionAspect 用户账号 {}", account);

            if (StringUtils.isBlank(account)) {
                throw new RuntimeException("获取不到用户登陆信息");
            }

            // 判断用户是否有该接口权限
            boolean hasPermission = StpUtil.hasPermission(permission);
            log.warn("AuthPermissionAspect 是否拥有权限 {}", hasPermission);

            if (!hasPermission) {
                throw new RuntimeException("抱歉，你未拥有该接口权限！");
            }
        }
    }

}
